<template>
  <div :class="{'mobile-table  mobile-min-height':showMobilePage}" class="return-money-container">
    <div v-if="!showMobilePage" style="position:relative;margin-bottom:16px;">
      <FilterInput ref="filterInput" v-model="paramsData" :filter-list="filterList" is-show-config show-search-btn class="FilterTool" @handelClick="queryClick" @queryEmpty="queryEmpty" />
      <div v-if="hasRouteAuth('crm:return:create')" class="table-top-opeator-bar">
        <createBtn text="生成报表" @click.native="handleCreate" />
      </div>
    </div>
    <div v-loading="listLoading" class="table-list">
      <u-table
        v-if="listData.items.length > 0"
        :data="listData.items"
        :border="true"
        :height="setTableHeight"
        :row-height="56"
        beautify-table
        header-drag-style
        use-virtual
        class="fb-table"
        element-loading-text="加载中..."
        empty-text="暂无数据"
        header-cell-class-name="order-data-header-cell"
        fit
        hightlight-current-row
        @sort-change="sortMethod">
        <u-table-column align="left" label="系统ID" width="120">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.returnId" :is-can-click="true" @handelClick="toDetail(scope.row)" />
          </template>
        </u-table-column>
        <u-table-column align="left" label="报表标题" width="120">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.reportName" />
          </template>
        </u-table-column>
        <u-table-column align="left" label="订单封账月份" width="160" prop="orderSealMonth" sortable="custom">
          <template slot-scope="scope">
            <div class="time">
              <span class="val">{{ scope.row.orderSealMonthStart | format('YYYY/MM') }}</span>
              <span class="separator">-</span>
              <span class="val">{{ scope.row.orderSealMonthEnd | format('YYYY/MM') }}</span>
            </div>
          </template>
        </u-table-column>
        <u-table-column align="left" label="流水到账月份" width="160" prop="financeSealMonth" sortable="custom">
          <template slot-scope="scope">
            <div class="time">
              <span class="val">{{ scope.row.financeSealMonthStart | format('YYYY/MM') }}</span>
              <span class="separator">-</span>
              <span class="val">{{ scope.row.financeSealMonthEnd | format('YYYY/MM') }}</span>
            </div>
          </template>
        </u-table-column>
        <u-table-column align="left" label="核销封账月份" width="160" prop="writeOffSealMonth" sortable="custom">
          <template slot-scope="scope">
            <div class="time">
              <span class="val">{{ scope.row.writeOffSealMonthStart | format('YYYY/MM') }}</span>
              <span class="separator">-</span>
              <span class="val">{{ scope.row.writeOffSealMonthEnd | format('YYYY/MM') }}</span>
            </div>
          </template>
        </u-table-column>
        <u-table-column align="left" label="类型" min-width="90">
          <template slot-scope="scope">
            {{ scope.row.returnType | typeFilter }}
          </template>
        </u-table-column>
        <u-table-column align="left" label="销售" min-width="120">
          <template slot-scope="scope">
            <CheckUserInfo :user-id="scope.row.saleId" :label="scope.row.saleName" />
          </template>
        </u-table-column>
        <u-table-column align="left" label="状态" min-width="90">
          <template slot-scope="scope">
            <StatusText :color="['#406eff','#31cc9c','red'][scope.row.status]" :text="scope.row.status | statusFilter" />
          </template>
        </u-table-column>
        <u-table-column align="left" label="创建人" min-width="120">
          <template slot-scope="scope">
            <CheckUserInfo :user-id="scope.row.createId" :label="scope.row.createUser" />
          </template>
        </u-table-column>
        <u-table-column align="left" label="更新人" min-width="120">
          <template slot-scope="scope">
            <CheckUserInfo :user-id="scope.row.updateUserId" :label="scope.row.updateUser" />
          </template>
        </u-table-column>
        <u-table-column align="left" label="所属部门" min-width="110">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.departmentName" />
          </template>
        </u-table-column>
        <u-table-column align="left" label="创建时间" min-width="150" prop="createTime" sortable="custom">
          <template slot-scope="scope">
            {{ scope.row.createTime | format('YYYY/MM/DD HH:mm') }}
          </template>
        </u-table-column>
        <u-table-column :align="operateAlign" :width="operateWidth" :fixed="operateFix" label="操作">
          <template slot-scope="scope">
            <div v-if="!showMobilePage" class="flex-center">
              <div class="button-text" @click="toDetail(scope.row)">查看</div>
              <div v-if="userInfo.id === Number(scope.row.createId) || hasRouteAuth('crm:return:delete')" class="button-text bl" @click="toDel(scope.row)">删除</div>
            </div>
            <tableOperateBtn v-else>
              <el-dropdown-item style="width:90px;text-align: center" @click.native="toDetail(scope.row)">
                <div style="font-size: 14px">查看</div>
              </el-dropdown-item>
              <el-dropdown-item v-if="userInfo.id === Number(scope.row.createId) || hasRouteAuth('crm:return:delete')" style="width:90px;text-align: center" @click.native="toDel(scope.row)">
                <div>删除</div>
              </el-dropdown-item>
            </tableOperateBtn>
          </template>
        </u-table-column>
      </u-table>
      <empty-placeholder v-else-if="!listData.isInit" style="margin-bottom: 24px" />
    </div>
    <el-row v-if="showMobilePage" type="flex" justify="left">
      <el-pagination
        v-show="listData.total > 0"
        :current-page.sync="page"
        :page-size="perPage"
        :total="listData.total"
        :small="true"
        :page-sizes="[20, 50, 100, 250, 500]"
        :layout="pageLayout"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-row>
    <fixed-pagination v-show="listData.total > 0">
      <template v-if="showMobilePage">
        <FilterInput ref="filterInput" v-model="paramsData" :filter-list="filterList" show-mobile-icon is-show-config show-search-btn class="FilterTool" @handelClick="queryClick" @queryEmpty="queryEmpty" />
        <createBtn v-if="hasRouteAuth('crm:return:create')" text="生成报表" mobile-table @click.native="handleCreate"/>
      </template>
      <template v-else>
        <span style="flex:1;"/>
        <el-pagination
          :current-page="page"
          :page-size="perPage"
          :total="listData.total"
          :page-sizes="[20, 50, 100, 250, 500]"
          layout="total, prev, pager, next, sizes, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </template>
    </fixed-pagination>
    <rangeDialog ref="resetRange" is-cache @submit="handleSubmit" />
  </div>
</template>

<script>
// api
import { getDepartmentAll } from '@/api/config';
import { getReturnReportList, deleteReturnList, createReturnReport } from '@/api/customer';
// tool
import { format } from '@/filters/date';
import { mapState } from 'vuex';
import { hasRouteAuth } from '@/utils/permission';
import { showModal } from '@/utils/message';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
// components
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import rangeDialog from './components/rangeDialog';
import createBtn from '@/components/Common/baseComponent/createBtn';
import axios from 'axios';

export default {
  components: { EmptyPlaceholder, rangeDialog, createBtn },
  filters: {
    format,
    typeFilter(num) {
      const arr = ['欠款分布', '到账分布'];
      return arr[Number(num)] || '--';
    },
    statusFilter(num) {
      const arr = ['生成中', '已完成', '已失败'];
      return arr[Number(num)] || '--';
    }
  },
  mixins: [TableAdaptive, mobileTable],
  data() {
    return {
      page: 1,
      perPage: 20,
      listData: {
        items: [],
        isInit: true
      },
      sortName: '',
      sortType: '',
      listLoading: false,
      paramsData: {},
      deptTreeList: [],
      rangeKeyArr: [
        { attr: 'orderSealMonth', start: 'orderSealMonthStart', end: 'orderSealMonthEnd', type: 'time' },
        { attr: 'financeSealMonth', start: 'financeSealMonthStart', end: 'financeSealMonthEnd', type: 'time' },
        { attr: 'writeOffSealMonth', start: 'writeOffSealMonthStart', end: 'writeOffSealMonthEnd', type: 'time' }
      ],
      cancelToken: null
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    filterList() {
      return [
        { keyword: 'reportName', name: '报表标题', labelWidth: '96px', type: 'input' },
        { keyword: 'returnId', name: '系统ID', labelWidth: '96px', type: 'input' },
        { keyword: 'sale', name: '销售', labelWidth: '96px', type: 'input' },
        { keyword: 'createUser', name: '创建人', labelWidth: '96px', type: 'input' },
        {
          keyword: 'returnType', name: '类型', type: 'select', labelWidth: '96px',
          options: [{ value: -1, label: '全部' }, { value: 0, label: '欠款分布' }, { value: 1, label: '到账分布' }]
        },
        {
          keyword: 'status', name: '状态', type: 'select', labelWidth: '96px',
          options: [{ value: -1, label: '全部' }, { value: 0, label: '生成中' }, { value: 1, label: '已完成' }, { value: 2, label: '已失败' }]
        },
        { keyword: 'departmentId', name: '所属部门', labelWidth: '96px', type: 'cascaderSelectWithChild', childrenVal: 'children', options: this.deptTreeList },
        { keyword: 'orderSealMonth', name: '订单封账月份', timeType: 'monthrange', type: 'rangeDate', labelWidth: '96px', format: 'yyyy/MM', startPlaceholder: '开始时间', endPlaceholder: '结束时间' },
        { keyword: 'financeSealMonth', name: '流水到账月份', timeType: 'monthrange', type: 'rangeDate', labelWidth: '96px', format: 'yyyy/MM', startPlaceholder: '开始时间', endPlaceholder: '结束时间' },
        { keyword: 'writeOffSealMonth', name: '核销封账月份', timeType: 'monthrange', type: 'rangeDate', labelWidth: '96px', format: 'yyyy/MM', startPlaceholder: '开始时间', endPlaceholder: '结束时间' }
      ];
    },
    tableOutsideHeight() {
      return this.showMobilePage ? 165 : 0;
    }
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'paymentReceived') {
      to.meta.isChange = true;
    } else {
      to.meta.isChange = false;
    }
    next();
  },
  activated() {
    if (this.$route.meta.isChange) {
      this.fetchData();
    } else {
      const hasDefaultPresetFilter = this.$refs.filterInput && this.$refs.filterInput.hasDefaultPresetFilter;
      // 当预设的默认筛选且为第一次进入页面时，不请求数据（会在 filterTool 组件进行筛选）
      if (!this.listData.isInit || !hasDefaultPresetFilter) {
        this.queryEmpty();
      }
    }
  },
  created() {
    this.queryDeptTreeList();
  },
  methods: {
    hasRouteAuth,
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.fetchData();
    },
    fetchData(reset = false) {
      if (this.cancelToken) this.cancelToken.cancel('cancel');
      const source = axios.CancelToken.source(); // 用于取消请求
      this.cancelToken = source;

      if (reset) this.page = 1;
      const params = JSON.parse(JSON.stringify(this.paramsData));
      this.rangeKeyArr.forEach(i => {
        if (params[i.attr] && params[i.attr].length === 2) {
          params[i.start] = Math.round(params[i.attr][0] / 1000);
          params[i.end] = this.getMonthEnd(params[i.attr][1]);
          delete params[i.attr];
        }
      });
      if (params.departmentId) {
        params.departmentId = params.departmentId.join(',');
      }
      params.page = this.page;
      params.perPage = this.perPage;
      params.sortType = this.sortType || '';
      params.sortName = this.sortName || '';
      this.listLoading = true;
      getReturnReportList(params, source.token).then(res => {
        this.listLoading = false;
        if (res.code === 200) {
          this.listData = res.data;
        }
        this.listData.isInit = false;
      });
    },
    getMonthEnd(time) {
      time = time.toString().length === 10 ? time * 1000 : time;
      const start = new Date(time);
      const nowYear = start.getFullYear(); // 当前年
      const nextMonth = start.getMonth() + 1; // 当前月

      let endDate = new Date(nowYear, nextMonth, 0, '23', '59', '59').valueOf();
      endDate = Math.round(endDate / 1000);
      return endDate;
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsData = {};
      this.queryClick();
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true);
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.fetchData();
    },
    // 部门
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    handelArr(arr) {
      if (!arr || arr.length === 0) return '';
      return arr.map(i => i.userName).join(',');
    },
    toDetail(item) {
      sessionStorage.setItem('returnStatus', item.status);
      sessionStorage.setItem('returnType', item.returnType);
      localStorage.setItem('returnData', JSON.stringify(item));
      this.$router.push({
        name: 'paymentReceived',
        params: {
          returnId: item.id
        }
      });
    },
    toDel(item) {
      showModal('请确定是否删除').then(() => {
        deleteReturnList({ id: item.id }).then(_ => {
          this.$message.success('删除成功');
          if (this.page > 1 && this.perPage * (this.page - 1) + 1 === this.listData.total) {
            this.page--;
          }
          this.fetchData();
        });
      });
    },
    handleCreate() {
      this.$refs.resetRange.openDialog();
    },
    handleSubmit(params) {
      createReturnReport(params).then(res => {
        if (res.code === 200) {
          this.$message.success('请求成功');
          this.$refs.resetRange.handleClose();
          this.fetchData();
        } else {
          this.$message.error(res.message);
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.return-money-container{
  margin: 16px 16px 0 16px;
  background-color: #fff;
  padding: 20px 24px 55px 24px;
  min-height: calc(100vh - 64px);
  .table-list {
    margin-top: 16px;
  }
}
.time {
  display: flex;
  .separator {
    margin: 0 5px;
  }
}
.flex-center {
  display: flex;
  align-items: center;
}
</style>
